package com.prashantdctm.config;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.DefaultCredentialsProvider;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HTMLParserListener;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;

public class AppConfigServlet extends HttpServlet {
	/**
	 * 
	 */
	private static WebClient webClient = null;
	private static StringBuffer messageLog = new StringBuffer();
	String htmlHeader = "<HTML><HEAD><TITLE> Request Headers</TITLE></HEAD><BODY>";
    String htmlFooter = "</BODY></HTML>";
    
	public static void main(String[] args) throws Exception {
	}
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
		initWebClient();
		initLog();
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		HtmlPage page = null;
		if(req.getParameter("url")!= null) {
			 page = webClient.getPage(req.getParameter("url"));
		} else {
			 page = webClient.getPage("http://prashantdctm2.appspot.com/AppConfigServlet?aa=000");
		}
		
		out.println(htmlHeader);
		
		out.println("<p/>page.asText()");
		out.println("<textarea rows=10 cols=100>");
		out.println(page.asText());
		out.println("</textarea>");
		
		out.println("<p/>Context");
		out.println("<textarea rows=10 cols=100>");
		ServletContext context = getServletContext();
		out.println("getServerInfo() name: "
				+ getServerInfoName(context.getServerInfo()));
		out.println("getServerInfo() version: "
				+ getServerInfoVersion(context.getServerInfo()));
		out.println("context.getAttributeNames():");
		Enumeration e = context.getAttributeNames();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			out.println("  context.getAttribute(\"" + name + "\"): "
					+ context.getAttribute(name));
		}
		out.println("</textarea>");
		
	    
		out.println("<p/>Request Parameters");
		out.println("<textarea rows=10 cols=100>");
		Map params = req.getParameterMap();
	    Iterator i = params.keySet().iterator();
	    while ( i.hasNext() )
	      {
	        String key = (String) i.next();
	        String value = ((String[]) params.get( key ))[ 0 ];
	        out.println("Param: "+key+" Value: "+value);
	      }
	    out.println("</textarea>");
	    
	    out.println("<p/>Others");
	    out.println("<textarea rows=10 cols=100>");
	    out.println("req.getRemoteAddr(): "+req.getRemoteAddr());
	    out.println("req.getRemoteHost(): "+req.getRemoteHost());
	    e = req.getHeaderNames();
	    String headers = null;
	    while (e.hasMoreElements()) {
		      headers = (String) e.nextElement();
		      if (headers != null) {
		        out.println(headers+": " + req.getHeader(headers));
		      }
		    }
		
		out.println("</textarea>");
		
	    
	    out.println(htmlFooter);
    }
	
	private String getServerInfoName(String serverInfo) {
		int slash = serverInfo.indexOf('/');
		if (slash == -1)
			return serverInfo;
		else
			return serverInfo.substring(0, slash);
	}

	private String getServerInfoVersion(String serverInfo) {
		// Version info is everything between the slash and the space
		int slash = serverInfo.indexOf('/');
		if (slash == -1)
			return null;
		int space = serverInfo.indexOf(' ', slash);
		if (space == -1)
			space = serverInfo.length();
		return serverInfo.substring(slash + 1, space);
	}
	
	
	  
	  public static void initWebClient() {
			try {
				webClient = new WebClient();
				
				webClient.setRefreshHandler(new RefreshHandler() {
					public void handleRefresh(Page page, URL url, int arg)
							throws IOException {
						
					}
				});
				// http://www.ozdroid.com/#!BLOG/2010/10/12/
				// How_to_Make_Google_AppEngine_Applications_Ajax_Crawlable
				// webClient.setWebConnection(new UrlFetchWebConnection(webClient));

				// webClient.setProxyConfig(pc);
				webClient.setHTMLParserListener(HTMLParserListener.LOG_REPORTER);
				webClient.setPopupBlockerEnabled(false);
				webClient.setTimeout(50000); // timout in ms
				webClient.setRedirectEnabled(true); // follow redirects
				webClient.setThrowExceptionOnFailingStatusCode(false);
				webClient.setJavaScriptEnabled(true);
				webClient.setThrowExceptionOnScriptError(false);
				webClient.setUseInsecureSSL(true);
				webClient.setCssEnabled(true);
				webClient.getCookieManager().setCookiesEnabled(true);
				customLog("Cokkie enabled "
						+ webClient.getCookieManager().isCookiesEnabled());
				// webClient.setTimeout(timeout);
			} catch (Exception e) {
				System.out.println("error initializing webclient)");
				e.printStackTrace();
			}
		}

		public static void initLog() {
			messageLog
					.append("<span style='font-family:Courier New, courier,monospace;font-style:normal;font-size:12px;'>");
		}
		
		public static void customLog(String msg) {
			messageLog.append("<br>" + msg);
			//log.info(msg);
		}
		public static void getCookie(HtmlPage page) {
			StringBuffer cookieHeader = new StringBuffer();
			customLog("");
			customLog("Response Header:");
			List rHdrs1 = page.getWebResponse().getResponseHeaders();
			for (int i = 0; i < rHdrs1.size(); i++) {
				Object o = rHdrs1.get(i);
				
				customLog(o.toString());
				if(o.equals("Set-Cookie")) {
					StringTokenizer stk = new StringTokenizer(o.toString(), ":");
					while(stk.hasMoreTokens()){
						stk.nextToken();
						cookieHeader.append(stk.nextToken());
					}
				}
			}
			/*WebResponse response = page.getWebResponse();
			WebRequest request = response.getWebRequest();

			customLog("Request Header:");
			List param = request.getRequestParameters();
			for (int i = 0; i < param.size(); i++) {
				Object o = param.get(i);
				System.out.println(o);
			}*/
			
			
			Set<Cookie> cookies = webClient.getCookieManager().getCookies();
			for (Cookie cookie : cookies) {
				customLog("CookieName: " + cookie.getName() + " CookieValue: "
						+ cookie.getValue());
				cookieHeader.append(cookie.getName()+"="+cookie.getValue()+";");
				/*Cookie cookieToSend = new Cookie(cookie.getName(), cookie
						.getValue());
				webClient.getCookieManager().addCookie(cookieToSend);*/
				// webClient.addRequestHeader(cookie.getName(), cookie.getValue());
			}
			System.out.println(cookieHeader.toString());
			webClient.addRequestHeader("Cookie", cookieHeader.toString());

		}
}

